package TCP.Demo2;

// ChatClient.java
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ChatClient {
    private static PrintWriter writer;
    private static BufferedReader reader;

    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 8888)) {
            System.out.println("已连接到聊天服务器");

            // 获取输入输出流
            writer = new PrintWriter(socket.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 创建线程接收服务器消息
            Thread receiverThread = new Thread(() -> {
                try {
                    String message;
                    while ((message = reader.readLine()) != null) {
                        System.out.println(message);
                    }
                } catch (IOException e) {
                    System.out.println("与服务器断开连接");
                }
            });
            receiverThread.start();

            // 主线程处理用户输入
            Scanner scanner = new Scanner(System.in);
            String userInput;
            while (scanner.hasNextLine()) {
                userInput = scanner.nextLine();
                writer.println(userInput);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
